const storageAvailable = (type: string) => {
  let storage;
  try {
    storage = window[type];
    const x = '__storage_test__';
    storage.setItem(x, x);
    storage.removeItem(x);
    return true;
  } catch (e) {
    return (
      e instanceof DOMException &&
      (e.code === 22 ||
        e.code === 1014 ||
        e.name === 'QuotaExceededError' ||
        e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
      storage &&
      storage.length !== 0
    );
  }
};

const Tip = () => {
  alert('请启用缓存功能');
};

let local;
if (storageAvailable('localStorage')) {
  local = {
    set: (key: string, val: any): void => {
      try {
        localStorage.setItem(`${APP_NAME}/${key}`, val);
      } catch (e) {
        alert(e);
      }
    },
    get: (key: string): any => {
      try {
        return localStorage.getItem(`${APP_NAME}/${key}`) || '';
      } catch (e) {
        alert(e);
      }
    },
    remove: (key: string): void => {
      try {
        localStorage.removeItem(`${APP_NAME}/${key}`);
      } catch (e) {
        alert(e);
      }
    },
    clear: (): void => {
      try {
        localStorage.clear();
      } catch (e) {
        alert(e);
      }
    },
  };
} else {
  Tip();
}

let session;
if (storageAvailable('sessionStorage')) {
  session = {
    set: (key: string, val: any): void => {
      try {
        sessionStorage.setItem(`${APP_NAME}/${key}`, val);
      } catch (e) {
        alert(e);
      }
    },
    get: (key: string): any => {
      try {
        return sessionStorage.getItem(`${APP_NAME}/${key}`) || '';
      } catch (e) {
        alert(e);
      }
    },
    remove: (key: string): void => {
      try {
        sessionStorage.removeItem(`${APP_NAME}/${key}`);
      } catch (e) {
        alert(e);
      }
    },
    clear: (): void => {
      try {
        sessionStorage.clear();
      } catch (e) {
        alert(e);
      }
    },
  };
} else {
  Tip();
}

export const Local: LocalStorage | undefined = local;
export const Session: SessionStorage | undefined = session;
